#include "queue_stack.h"

int create_queue(queue_t **p){
    if(NULL == p){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    *p = (queue_t *)malloc(sizeof(queue_t));
    if(NULL == *p){
        printf("内存分配失败\n");
        return -1;
    }
    (*p)->front = (*p)->rear = NULL;
    (*p)->count = 0;
    return 0;
}

int clean_queue(queue_t *my_queue){
    if(NULL == my_queue){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    // 循环头删所有数据节点
    node_t *pdel = NULL;
    while(NULL != my_queue->front){
        pdel = my_queue->front;
        my_queue->front = pdel->next;
        free(pdel);
    }
    pdel = NULL;
    my_queue->rear = NULL;
    my_queue->count = 0;
    return 0;
}

int destroy_queue(queue_t **my_queue){
    if(NULL == my_queue || NULL == *my_queue){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    // 先清空再销毁 防止内存泄露
    clean_queue(*my_queue);
    free(*my_queue);
    *my_queue = NULL;
    return 0;
}

int push_queue(queue_t *my_queue, int num){
    if(NULL == my_queue){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    
    node_t *pnew = (node_t *)malloc(sizeof(node_t));
    if(NULL == pnew){
        printf("内存分配失败\n");
        return -1;
    }
    pnew->data = num;
    pnew->next = NULL;

    if(NULL == my_queue->front && NULL == my_queue->rear){
       
        my_queue->front = pnew;
        my_queue->rear = pnew;
    }else{
        
        my_queue->rear->next = pnew;
        my_queue->rear = pnew;
    }
    my_queue->count++;
    return 0;
}

int is_empty(queue_t *my_queue){
    if(NULL == my_queue){
        printf("入参为NULL 请检查\n");
        return -1;
    }

    return NULL == my_queue->front && NULL == my_queue->rear ? 1 : 0;
}

int pop_queue(queue_t *my_queue, int *buff){
    if(NULL == my_queue || NULL == buff){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    if(is_empty(my_queue)){
        return -1;
    }
    *buff = my_queue->front->data;
    node_t *pdel = my_queue->front;
    my_queue->front = pdel->next;
    free(pdel);
    pdel = NULL;
    if(NULL == my_queue->front){
        my_queue->rear = NULL;
    }
    my_queue->count--;
    return 0;
}

int print_queue(queue_t *my_queue){
    if(NULL == my_queue){
        printf("入参为NULL 请检查\n");
        return -1;
    }
    node_t *ptemp = my_queue->front;
    while(NULL != ptemp){
        printf("%d ", ptemp->data);
        ptemp = ptemp->next;
    }
    printf("\n");
    return 0;
}